package com.weblog.weblog.jwt.handler;

import com.weblog.weblog.common.domain.dos.UserIpAddressDO;
import com.weblog.weblog.common.domain.mapper.UserIpAddressMapper;
import com.weblog.weblog.common.utils.IpUtil;
import com.weblog.weblog.common.utils.Response;
import com.weblog.weblog.jwt.module.LoginRspVo;
import com.weblog.weblog.jwt.utils.JwtTokenHelper;
import com.weblog.weblog.jwt.utils.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * @author gc
 * @class_name RestAuthenticationSuccessHandler
 * @date 2023年09月15日 20:18
 */

@Slf4j
@Component
public class RestAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private final JwtTokenHelper jwtTokenHelper;
    private final UserIpAddressMapper userIpAddressMapper;

    public RestAuthenticationSuccessHandler(JwtTokenHelper jwtTokenHelper, UserIpAddressMapper userIpAddressMapper) {
        this.jwtTokenHelper = jwtTokenHelper;

        this.userIpAddressMapper = userIpAddressMapper;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();

        String username = userDetails.getUsername();
        String token = jwtTokenHelper.generateToken(username);

        //获取用户ip
        String ip = IpUtil.getIp(request);
        String ipAddress = IpUtil.getIp2region(ip);
        String userAgent = IpUtil.getUserAgent(request);

        userIpAddressMapper.insert(UserIpAddressDO.builder()
                        .username(username)
                        .ip(ip)
                        .loginTime(LocalDateTime.now())
                        .address(ipAddress)
                        .userAgent(userAgent)
                        .build());

        // 返回 Token
        LoginRspVo loginRspVo = LoginRspVo.builder().token(token).build();

        ResultUtils.ok(response, Response.success(loginRspVo));
    }
}
